package com.bjpowernode.controller;


import com.bjpowernode.pojo.ProductInfo;
import com.bjpowernode.pojo.vo.ProductInfoVo;
import com.bjpowernode.service.ProductInfoService;
import com.bjpowernode.utils.FileNameUtil;
import com.github.pagehelper.PageInfo;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/prod")
public class ProductInfoController {

    public static final int PAGE_SIZE = 5;
    String imageName;

    //业务逻辑层对象
    @Autowired
    ProductInfoService productInfoService;

    //获取所有商品数据，不分页
    @RequestMapping("/getAll")
    public String getAll(HttpServletRequest request){
        List<ProductInfo> list = productInfoService.getAll();
        request.setAttribute("list",list);
        return "product";
    }

    //展示某一页的数据
    @RequestMapping("/split")
    public String split(HttpServletRequest request){
        PageInfo pageInfo = null;
        Object vo = request.getSession().getAttribute("prodVo");
        if (vo != null){
            //如果有页面信息等数据
            pageInfo = productInfoService.splitPageVo((ProductInfoVo)vo,PAGE_SIZE);
            //清除session中的prodVo
            request.getSession().removeAttribute("prodVo");
        }else{
            //拿到第1页的数据
            pageInfo = productInfoService.splitPage(1, PAGE_SIZE);
        }
        request.setAttribute("info",pageInfo);
        return "product";
    }

    //ajax分页处理
    @ResponseBody
    @RequestMapping("/ajaxsplit")
    public void ajaxsplit(ProductInfoVo vo, HttpSession session){
        PageInfo pageInfo = productInfoService.splitPageVo(vo,PAGE_SIZE);
        session.setAttribute("info",pageInfo);
    }

    //异步ajax上传文件
    @ResponseBody
    @RequestMapping("/ajaxImg")
    public Object ajaxImg(MultipartFile pimage,HttpServletRequest request){
        //获取生成的文件名称：UUID+上传图片的后缀
        imageName = FileNameUtil.getUUIDFileName()+FileNameUtil.getFileType(pimage.getOriginalFilename());
        //获取项目中图片存储路径
        String path = request.getServletContext().getRealPath("/image_big");
        //转存
        try {
            pimage.transferTo(new File(path+File.separator+imageName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //返回JSON对象，封装图片路径，使其能在页面上回显
        JSONObject object = new JSONObject();
        object.put("imgurl",imageName);
        return object.toString();
    }

    //增加商品
    @RequestMapping("/save")
    public String save(ProductInfo info,HttpServletRequest request){
        //增加商品页面传来的商品信息缺少图片名称和日期
        info.setpImage(imageName);
        info.setpDate(new Date());

        int num = -1;
        try {
            num = productInfoService.save(info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (num > 0){
            //增加成功，在页面上显示信息
            request.setAttribute("msg","商品增加成功！");
        }else{
            //增加失败，在页面上显示信息
            request.setAttribute("msg","商品增加失败");
        }
        //清空imageName,为了下一次增加或修改的异步ajax上传处理
        imageName = "";
        //转发到分页展示页面
        return "forward:/prod/split.action";
    }

    //跳转到查询页面
    @RequestMapping("/getById")
    public String getById(Integer pid,ProductInfoVo vo,HttpServletRequest request){
        ProductInfo info = productInfoService.getById(pid);
        request.setAttribute("prod",info);
        //将多条件和页码放入session中，更新处理结束后读取条件和页码进行处理
        request.getSession().setAttribute("prodVo",vo);
        return "update";
    }

    //更新商品信息
    @RequestMapping("/update")
    public String update(ProductInfo info,HttpServletRequest request){
        //如果使用异步ajax上传了图片，则imageName中有数据，否则为""
        if (!("".equals(imageName))){
            info.setpImage(imageName);
        }
        int num = -1;
        try {
            num = productInfoService.update(info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //判断是否更新成功
        if (num > 0){
            request.setAttribute("msg","商品更新成功！");
        }else {
            request.setAttribute("msg","商品更新失败！");
        }
        //将imageName置为空，为了下一次异步ajax上传图片
        imageName = "";
        return "forward:/prod/split.action";
    }


    //单个删除
    @RequestMapping("/delete")
    public String delete(int pid,ProductInfoVo vo,HttpServletRequest request){
        int num = -1;
        try {
            num = productInfoService.deleteById(pid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (num > 0){
            request.setAttribute("msg","删除成功！");
            request.getSession().setAttribute("deleteVo",vo);
        }else
            request.setAttribute("msg","删除失败！");
        return "forward:/prod/deleteAjaxSplit.action";
    }

    @ResponseBody
    @RequestMapping(value = "/deleteAjaxSplit",produces = "text/html;charset=UTF-8")
    public Object deleteAjaxSplit(HttpServletRequest request){
        PageInfo info = null;
        Object vo = request.getSession().getAttribute("deleteVo");
        if (vo != null){
            info = productInfoService.splitPageVo((ProductInfoVo)vo,PAGE_SIZE);
        }else{
            //获取第一页数据
            info = productInfoService.splitPage(1,PAGE_SIZE);
        }
        request.getSession().setAttribute("info",info);
        return request.getAttribute("msg");
    }

    //批量删除
    @RequestMapping("/deleteBatch")
    public String deletebatch(String pids,HttpServletRequest request){
        //将获取的id字符串分割
        String[] ids = pids.split(",");
        try {
            int num = productInfoService.deleteBatch(ids);
            if (num > 0){
                request.setAttribute("msg","批量删除成功！");
            }else{
                request.setAttribute("msg","批量删除失败！");
            }
        } catch (Exception e) {
            request.setAttribute("msg","当前商品不可删除！");
        }
        return "forward:/prod/deleteAjaxSplit.action";
    }



}
